<template>
    <div>
        <page-view>

            <template #tabBar>
                <el-tabs v-model="activeName" @tab-click="handleClick">
                    <el-tab-pane label="台账合计" name="first"> </el-tab-pane>
                    <el-tab-pane label="台账明细" name="second"></el-tab-pane>
                </el-tabs>

            </template>
            <template #option>
                <div class="btn-box">
                    <el-button type="primary" @click="exportDetail" :disabled="loading"
                        v-if="activeName == 'second'">导出</el-button>
                </div>
            </template>
            <template #form>
                <SearchForm :data-form="formInline" @on-search="onSearch" @onReset="onSearch">
                    <el-form-item prop="orgCodes" label-width="60px">

                        <!-- <el-select v-model="formInline.orgCodes" class="w100p" clearable filterable placeholder="请选择公司"
                            @change="getCostCenterList">
                            <el-option v-for="item in companyList " :key="item.departmentId"
                                :label="'[' + item.departmentId + ']' + item.departmentName" :value="item.departmentId" />
                        </el-select> -->
                        <companySearch :back-value="formInline.orgCodes" class="w100p" @select="selectCompany">
                        </companySearch>
                    </el-form-item>
                    <el-form-item prop="costCenterIds" label-width="60px">

                        <el-select v-model="formInline.costCenterIds" clearable class="w100p" filterable
                            placeholder="请选择成本中心">
                            <el-option v-for="item in costCenterList " :key="item.id"
                                :label="item.centerName + item.centerCode" :value="item.id">
                                <span style="float: left">{{ item.centerName }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px;">[{{
                                    item.centerCode
                                }}]</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="years" label-width="60px">
                        <el-input placeholder="请输入年度" v-model="formInline.years" clearable></el-input>
                    </el-form-item>

                    <el-form-item prop="budgetType" v-if="activeName == 'first'">
                        <el-select v-model="formInline.budgetType" clearable placeholder="请选择预算类型">
                            <el-option v-for="item in BUDGET_TYPE_LIST" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>


                    <el-form-item prop="categoryCodes" v-if="activeName == 'second'">

                        <SelectSearch :info="categoryCodeInfo" v-model:value="formInline.categoryCodes"
                            placeholder="请输入科目编码/名称"></SelectSearch>
                    </el-form-item>
                    <el-form-item prop="budgetPeriod" label-width="60px" v-if="activeName == 'second'">
                        <el-input placeholder="请输入预算期间" v-model="formInline.budgetPeriod" clearable></el-input>
                    </el-form-item>

                </SearchForm>
            </template>

            <template #table="tableScope">
                <PubilcTable :table-data="tableData" :showIndex="true" :isSlot="false"
                    :list-config="activeName == 'first' ? BUDGGE_QUERY_CONFIG : BUDGGE_QUERY_ACCOUNT_CONFIG"
                    :page-data="pageData" @on-action="onAction" :translateTextDeal="translateTextDeal"
                    @on-linkClick="linkClick" :tableHeight="tableScope.tableHeight" :loading="loading">
                    <template #usedBudget>
                        <el-table-column width="140" label="已使用额度" prop="usedBudget">
                            <template v-slot="{ row }">
                                <el-button link @click="toDetail(row)">{{
                                    row.usedBudget ? `￥${MoneyFormat(row.usedBudget.toFixed(2))}` : '￥ 0.00' }}</el-button>
                            </template>
                        </el-table-column>
                    </template>
                </PubilcTable>
            </template>

        </page-view>

    </div>
</template>
<script  setup name="BudgetQuery">
import { reactive } from 'vue'
import { BUDGGE_QUERY_CONFIG, BUDGET_TYPE_LIST, BUDGGE_QUERY_ACCOUNT_CONFIG } from './Common/config'
import { statusText } from '@/util/index'
import { MoneyFormat } from '@/util/filterConfig'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserOutsideStore } from '@/store/modules/user'
import { downloadFile } from '@/util/downFile'
import dayjs from 'dayjs'
import api from '@/api'

const router = useRouter()

const user = useUserOutsideStore()

const formInline = ref({
    years: new Date().getFullYear(),
    budgetType: '',
    budgetName: '',
    costCenterIds: '',
    orgCodes: [],
    categoryCodes: '',
    budgetPeriod: ''

})
const pageData = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
})

const loading = ref(false)

const tableData = ref([])

const costCenterList = ref([]) // 成本中心

const companyList = ref([])

const activeName = ref('first')

const categoryCodeInfo = ref({
    interfaceName: 'budgetSubjectList',
    label: 'categoryName',
    value: 'categoryCode',
    fileName: 'budgetConfig',
    keyword: 'codeOrName',
})

const onSearch = () => {
    pageData.value.pageNum = 1
    getList()
}
const getParams = () => {
    let parms = {
        ...pageData.value,
        ...formInline.value
    }
    if (parms.orgCodes && parms.orgCodes != '') parms.orgCodes = [parms.orgCodes]
    if (parms.costCenterIds && parms.costCenterIds != '') parms.costCenterIds = [parms.costCenterIds]
    if (parms.orgCodes == '') parms.orgCodes = []
    if (parms.costCenterIds == '') parms.costCenterIds = []
    if (activeName.value == 'first') {
        delete parms.budgetPeriod
        delete parms.categoryCodes
    }
    if (activeName.value == 'second') {

        if (parms.categoryCodes && parms.categoryCodes != '') {
            parms.categoryCodes = [parms.categoryCodes]
        } else {
            parms.categoryCodes = []
        }

    }
    return parms
}

// 获取列表数据
const getList = () => {

    loading.value = true

    let interfaceNameObj = {
        first: 'budgetQueryList',
        second: 'budgetQueryAccountList'
    }

    api.budgetConfig[interfaceNameObj[activeName.value]](getParams()).then(res => {
        loading.value = false
        const { list, total } = res
        list.forEach(item => {
            item['orgText'] = `（${item.orgCode}）${item.orgName || ''}`

        })
        pageData.value.total = total
        tableData.value = list

    })

}



const translateTextDeal = (item, val, row) => {
    let text = ''
    const moneyFieldList = ['totalAmount', 'adjustmentAmount', 'usedBudgetAmount', 'totalBudgetAmount', 'availableBudgetAmount', 'totalBudget', 'adjustmentBudget', 'availableBudget']
    if (moneyFieldList.includes(item.alias)) text = val ? `￥${MoneyFormat(val.toFixed(2))}` : '￥ 0.00'


    if (item.alias == 'curTotalAmount') {
        let curMoney = (Number(row.totalAmount) + Number((row.adjustmentAmount || 0))).toFixed(2)
        text = curMoney ? `￥${MoneyFormat(curMoney)}` : '￥ 0.00'
    }
    if (item.alias == 'budgetType') text = statusText(BUDGET_TYPE_LIST, val)

    return text

}
const selectCompany = (obj) => {
    formInline.value.orgCodes = obj.orgCode
}

const handleClick = (tab, event) => {
    onSearch()
}
const linkClick = ([item, data]) => {
    console.log(item, data)
    if (item == 'budgetName') {
        router.push({
            name: 'staffingEdit',
            query: { id: data.id, type: 'look', centerName: data.centerName }
        })
    }


}
const handleClose = () => {
    dialogVisible.value = false
    dialogVisibleHistory.value = false
    dialogVisibleAudit.value = false
}
// 获取成本中心的数据
const getCostCenterList = (orgCode) => {
    const parms = {
        // orgCode,
        pageNum: 1,
        pageSize: 10000,

    }
    api.budgetManger.CBcostCenterList(parms).then(res => {
        const { list } = res
        costCenterList.value = list

    })

}


// 获取公司数据
const getCompanyList = () => {
    api.publicApi.emailQueryCompany({ email: user.userInfo.email }).then(res => {
        companyList.value = res

    })

}


const toDetail = ({ budgetNo, startTime, endTime, budgetCategoryRelationId, budgetPeriod, years }) => {
    let query = {
        budgetNo,
        type: 'USE',
        startTime: dayjs(startTime).format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs(endTime).format('YYYY-MM-DD HH:mm:ss'),
        budgetCategoryRelationId
    }
    if (budgetPeriod == '年') {
        let curYears = years.replace("年",'')

        query.startTime = `${curYears}-01-01 00:00:00`
        query.endTime = `${curYears}-12-31 23:59:59`
    }
    router.push({
        name: 'budgetClearOrder',
        query
    })
}

const exportDetail = () => {
    loading.value = true

    api.budgetConfig.budgetAccountDetailExport(getParams()).then((res) => {

        downloadFile(res, '台账明细导出', 'xlsx')
        ElMessage({
            type: 'success',
            message: '导出成功!'
        });
        loading.value = false

    })
}
// 列表操作 分页
const onAction = ([item, row]) => {
    const obj = {
        'pageNum': getList,
        'pageSize': onSearch
    }
    if (typeof item === 'string') {
        pageData.value[item] = row
        obj[item]()
    } else {
        obj[item.alias](row)
    }
}
onActivated(() => {

    onSearch()
    getCompanyList()
    getCostCenterList()

})
</script>
